package com.crowntit.trigger.http;

import com.alibaba.fastjson.JSON;
import com.crowntit.api.IMarketIndexService;
import com.crowntit.api.dto.GoodsMarketRequestDTO;
import com.crowntit.api.dto.GoodsMarketResponseDTO;
import com.crowntit.api.response.Response;
import com.crowntit.domain.activity.model.entity.*;
import com.crowntit.domain.activity.service.IIndexGroupBuyMarketService;
import com.crowntit.types.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/gbm/index/")
public class MarketIndexController implements IMarketIndexService {

    @Resource
    private IIndexGroupBuyMarketService groupBuyMarketService;

    @Override
    @RequestMapping(value = "query_group_buy_market_config", method = RequestMethod.POST)
    public Response<GoodsMarketResponseDTO> queryGoodsMarketConfig(@RequestBody GoodsMarketRequestDTO requestDTO) throws Exception {
        log.info("查询商品详情页信息");

        String userId = requestDTO.getUserId();
        String source = requestDTO.getSource();
        String channel = requestDTO.getChannel();
        String goodsId = requestDTO.getGoodsId();

        if (StringUtils.isBlank(source) || StringUtils.isBlank(channel) || StringUtils.isBlank(goodsId)) {
            return Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.ILLEGAL_PARAMETER.getCode())
                    .info(ResponseCode.ILLEGAL_PARAMETER.getInfo())
                    .build();
        }

        // 商品信息查询
        SkuActivityEntity skuActivityEntity = groupBuyMarketService.queryScSkuInfo(ScSkuEntity.builder()
                .channel(channel)
                .source(source)
                .goodsId(goodsId)
                .build());
        if (skuActivityEntity == null){
            log.info("当前商品不存在");
            return Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.E0007.getCode())
                    .info(ResponseCode.E0007.getInfo())
                    .build();
        }

        // 如果当前商品没有进行中的活动
        Long activityId = skuActivityEntity.getActivityId();
        if (activityId == null || activityId == 0) {
            log.info("当前商品没有进行中的活动");
            return Response.<GoodsMarketResponseDTO>builder()
                    .code(ResponseCode.E0008.getCode())
                    .info(ResponseCode.E0008.getInfo())
                    .data(GoodsMarketResponseDTO.builder()
                            .goods(GoodsMarketResponseDTO.Goods.builder()
                                    .goodsName(skuActivityEntity.getGoodsName())
                                    .goodsId(skuActivityEntity.getGoodsId())
                                    .originalPrice(skuActivityEntity.getOriginalPrice())
                                    .deductionPrice(skuActivityEntity.getOriginalPrice())
                                    .build())
                            .build())
                    .build();
        }

        // 优惠试算
        BigDecimal deductionPrice = BigDecimal.ZERO;
        BigDecimal payPrice = skuActivityEntity.getOriginalPrice();
        if (StringUtils.isNotBlank(userId)) {
            TrialBalanceEntity trialBalanceEntity = groupBuyMarketService.indexMarketTrial(MarketProductEntity.builder()
                    .goodsId(goodsId)
                    .activityId(activityId)
                    .userId(userId)
                    .source(source)
                    .channel(channel)
                    .build());
            payPrice = trialBalanceEntity.getPayPrice();
            deductionPrice = trialBalanceEntity.getDeductionPrice();
        }

        // 组队信息查询
        List<UserGroupBuyTeamDetailEntity> teamEntityList = groupBuyMarketService.queryInProgressTeam(IndexTeamQueryEntity.builder()
                .userId(userId)
                .activityId(activityId)
                .source(source)
                .channel(channel)
                .goodsId(goodsId)
                .build());
        List<GoodsMarketResponseDTO.Team> teamList = new ArrayList<>();

        if (!teamEntityList.isEmpty()) {
            for (UserGroupBuyTeamDetailEntity userGroupBuyTeamDetailEntity : teamEntityList) {
                teamList.add(GoodsMarketResponseDTO.Team.builder()
                        .teamId(userGroupBuyTeamDetailEntity.getTeamId())
                        .activityId(userGroupBuyTeamDetailEntity.getActivityId())
                        .userId(userGroupBuyTeamDetailEntity.getUserId())
                        .targetCount(userGroupBuyTeamDetailEntity.getTargetCount())
                        .completeCount(userGroupBuyTeamDetailEntity.getCompleteCount())
                        .lockCount(userGroupBuyTeamDetailEntity.getLockCount())
                        .validStartTime(userGroupBuyTeamDetailEntity.getValidStartTime())
                        .validEndTime(userGroupBuyTeamDetailEntity.getValidEndTime())
                        .validTimeCountdown(GoodsMarketResponseDTO.Team.differenceDateTime2Str(new Date(), userGroupBuyTeamDetailEntity.getValidEndTime()))
                        .outTradeNo(userGroupBuyTeamDetailEntity.getOutTradeNo())
                        .build());
            }
        }

        GoodsMarketResponseDTO goodsMarketResponseDTO = GoodsMarketResponseDTO.builder()
                .goods(GoodsMarketResponseDTO.Goods.builder()
                        .goodsName(skuActivityEntity.getGoodsName())
                        .goodsId(goodsId)
                        .activityId(activityId)
                        .originalPrice(skuActivityEntity.getOriginalPrice())
                        .deductionPrice(deductionPrice)
                        .payPrice(payPrice)
                        .build())
                .teamList(teamList)
                .build();
        log.info("响应数据：{}", JSON.toJSONString(goodsMarketResponseDTO));
        return Response.<GoodsMarketResponseDTO>builder()
                .data(goodsMarketResponseDTO)
                .code(ResponseCode.SUCCESS.getCode())
                .info(ResponseCode.SUCCESS.getInfo())
                .build();
    }
}
